package nz.ac.massey.cs.asdc.patterns.xml.sax;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

/**
 * Content handler implementation which simply logs SAX events on the console.
 * @author Jens Dietrich
 */
public class ExtractRecipients implements ContentHandler {

	boolean toMode = false;
	boolean printContent = false;
	
	public void endDocument() throws SAXException {}

	public void startDocument() throws SAXException {}

	public void characters(char[] ch, int start, int length) throws SAXException {
		if (printContent) {
			char[] data = new char[length];
			for (int i=start;i<(start+length);i++) data[i-start]=ch[i];
			System.out.print(new String(data));
		}
	}

	public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {}

	public void endPrefixMapping(String prefix) throws SAXException {}

	public void skippedEntity(String name) throws SAXException {}

	public void setDocumentLocator(Locator locator) {}

	public void processingInstruction(String target, String data) throws SAXException {}

	public void startPrefixMapping(String prefix, String uri) throws SAXException {}

	public void startElement(String namespaceURI,String localName,String qName,Attributes atts) throws SAXException {
		if ("to".equals(localName)) toMode=true;
		else if (toMode && "email_address".equals(localName)) {
			printContent=true;
			System.out.print('<');
		}
		else if (toMode && "display_name".equals(localName)) {
			printContent=true;
			System.out.print(' ');
		}
	}
	
	public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
		if (localName.equals("to")) {
			toMode=false;
			System.out.println();
		}
		else if (toMode && "email_address".equals(localName)) {
			printContent=false;
			System.out.print('>');
		}
		else if (toMode && "display_name".equals(localName)) {
			printContent=false;
		}
	}




}
